package com.lookme.lmtool.cracker.filter.color;

import com.lookme.lmtool.cracker.CrackerConstants;
import com.lookme.lmtool.cracker.annotation.FilterAnnotation;
import com.lookme.lmtool.cracker.annotation.ParamAnnotation;
import com.lookme.lmtool.cracker.filter.AbstractFilter;
import com.lookme.lmtool.utils.ImageUtils;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@FilterAnnotation(groupName = CrackerConstants.FILTER_GROUP_NAME_COLOR,name="清除背景")
public class FilterClearBg extends AbstractFilter {
    @XStreamAsAttribute
    @ParamAnnotation(name = "清除背景颜色数量", desc = "清除背景颜色数量",inputType = ParamAnnotation.InputType.Spinner,max=20)
    int includeColorNumber=2;
    @XStreamAsAttribute
    @ParamAnnotation(name = "色彩阀值", desc = "色彩阀值",inputType = ParamAnnotation.InputType.Slider,max=256)
    int threshold=10;

    @XStreamAsAttribute
    @ParamAnnotation(name = "填充颜色", desc = "填充颜色",inputType = ParamAnnotation.InputType.ColorPicker,margin = {0,50,0,0})
    int color=0xffffff;

    @Override
    public BufferedImageOp getFilter() {
        return null;
    }

    @Override
    public BufferedImage filter(BufferedImage src, BufferedImage dest) {
        Map<Integer,Integer> colors=ImageUtils.getRangeColor(src,0,0,src.getWidth(),src.getHeight());
        List<Integer> includeColors=new ArrayList<Integer>();
        int cnt=0;
        for(Iterator it = colors.entrySet().iterator();it.hasNext();) {
            Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>) it.next();
            if(cnt<includeColorNumber){
                includeColors.add(entry.getKey());
                cnt++;
            }
        }
        int width = dest.getWidth();
        int height = dest.getHeight();
        int fillColor=-1;
        try {
            Color c = new Color(color);
            fillColor = c.getRGB();
        }catch(Exception e){

        }
        for (int y = 0; y <height; y++) {
            for (int x = 0; x < width; x++) {
                if (includeColors.contains(dest.getRGB(x, y))) {
                    dest.setRGB(x, y,fillColor);
                    continue;
                }
                boolean inColor = false;
                Color cc = new Color(dest.getRGB(x, y));
                for (Integer c2 : includeColors) {
                    Color c1 = new Color(c2);
                    if (Math.abs(c1.getRed() - cc.getRed() + c1.getGreen() - cc.getGreen() + c1.getBlue() - cc.getBlue()) < threshold) {
                        inColor = true;
                    }
                }
                if (inColor) {
                    dest.setRGB(x, y,fillColor);
                }
            }
        }
        return dest;
    }
}
